<?php

use think\Controller;
use think\facade\Config;
use think\Db;

// 应用公共文件
class Common extends Controller{

    public $token = "";

    # 初始验证Token
    public function __construct(\think\App $app = null){
        parent::__construct($app);
        # 获取头信息
        $headers = getallheaders();
        # 获取token并验证
        if(isset($headers["Authorization"])){
            $this->token = $this->CheckToken($headers["Authorization"]);
        }
    }

    # 语言包
    protected function Language($string){
        return $string;
    }

    # 加密、解密方法  $string 需要加密文本 。$operation "D"为解密，E为加密
    private function encrypt($string,$operation,$key=null){
        if($key === null){
            $key = Config::get("app.tokenEncrypt");
        }
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }

    // 生成Token
    public function BeToken($array){
        // 需要的值: uid、时间戳
        $string = json_encode($array,256);
        return $this->encrypt($string,"E")."d2";
    }

    // 检查Token
    public function CheckToken($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $admin = $this->encrypt($new_str,"D");
            $user = json_decode($admin,true);
            $token_info = ['time','uid'];
            if(Isset_all($user,$token_info)){
                $time = $user["time"];
                if($user["sev"]){
                    if($time+60*60*24*7 < time()){
                        // token过期
                        $array = [
                            "code" => 901,
                            "msg" => "身份验证已过期，请重新登录"
                        ];
                        echo json_encode($array,256);
                        exit();
                    }else{
                        $admin = Db::name("users")->where("user_id", $user["uid"])->find();
                        if(empty($admin)){
                            // 管理员不存在，token违法
                            $array = [
                                "code" => 801,
                                "msg" => "非法身份登录"
                            ];
                            echo json_encode($array,256);
                            exit();
                        }else{
                            return [
                                "uid" => $user["uid"]
                            ];
                        }
                    }
                }else{
                    if($time+60*60*24 < time()){
                        $array = [
                            "code" => 901,
                            "msg" => "身份验证已过期，请重新登录"
                        ];
                        echo json_encode($array,256);
                        exit();
                    }else{
                        $admin = Db::name("users")->where("user_id", $user["uid"])->find();
                        if(empty($admin)){
                            // 管理员不存在，token违法
                            $array = [
                                "code" => 801,
                                "msg" => "非法身份登录"
                            ];
                            echo json_encode($array,256);
                            exit();
                        }else{
                            return [
                                "uid" => $user["uid"]
                            ];
                        }
                    }
                }
            }else{
                // token违法
                $array = [
                    "code" => 801,
                    "msg" => "非法身份登录"
                ];
                echo json_encode($array,256);
                exit();
            }
        }else{
            // token违法
            $array = [
                "code" => 801,
                "msg" => "非法身份登录"
            ];
            echo json_encode($array,256);
            exit();
        }
    }

    # echo json
    protected function Code($code=null,$msg=false,$data=false,$options=256){
        $array = [];
        $array["code"] = $code;
        (is_bool($msg) && !$msg) ? false : ($msg == 403 ? $array["msg"] = $this->Language("服务器错误,请稍后重试") : $array["msg"] = $msg);
        (is_bool($data) && !$data) ? false : $array["data"] = $data;
        echo json_encode($array, $options);
        exit();
    }

}

/*批量验证isset*/
function Isset_all($type,$arr){
    foreach ($arr as $value){
        if(!isset($type[$value])){
            return false;
        }
    }
    return true;
}
